package com.ysl.netty.common;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LikeRedisTemplate {
    /**存放链接池实例*/
    private Map<String,Channel> ChannelRedisMap = new ConcurrentHashMap<>();

    /**
     * 存储对应的用户名与Netty链接实例
     * @param name 登录用户名
     * @param channel Netty链接实例
     */
    public void saveChannel(String name,Channel channel){
        String oldname = getUserId(channel);
        if(StrUtil.isEmpty(oldname))
        {
            ChannelRedisMap.put(name,channel);
        }
        else
        {
            if(!oldname.equals(name))
            {
                deleteChannel(oldname);
                ChannelRedisMap.put(name,channel);
            }
        }
    }

    /**
     * 获取存储池中的链接实例
     * @param name 登录用户名
     * @return {@link Channel 链接实例}
     */
    public Channel getChannel(String name){
        Channel channel=(Channel) ChannelRedisMap.get(name);
        return ChannelRedisMap.get(name);
    }

    /**
     * 删除存储池实例
     * @param name 登录用户名
     */
    public void deleteChannel(String name){
        ChannelRedisMap.remove(name);
    }

    /**
     * 获取储存池链接数
     * @return 在线数
     */
    public Integer getSize(){
        return ChannelRedisMap.size();
    }

    /**
     * 返回在线用户列表信息
     * @return 用户名列表
     */
    public List<String> getOnline() {
        List<String> result = new ArrayList<>();
        for (String key:ChannelRedisMap.keySet()){
            result.add(key);
        }
        return result;
    }

    public String getUserId(Channel channel){
        for (Map.Entry<String, Channel> entry : ChannelRedisMap.entrySet()) {
            Channel value = entry.getValue();
            if (channel == value){
                String key = entry.getKey();
                return key ;
            }
        }
        return null;
    }
}
